<template>
  <a-spin :spinning="confirmLoading">
    <!--    主表-->
    <j-form-container :disabled="formDisabled" ref="realForm">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="制度分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree-select
                v-decorator="['parentId', validatorRules.parentId]"
                style="width: 100%"
                placeholder="请选择制度分类"
                :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                :treeData="treeData"
                :replaceFields="replaceFields"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="制度名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['title', validatorRules.title]" placeholder="请输入名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-decorator="['remarks']" rows="4" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="上传附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--    子表-->
              <a-tabs>
                <a-tab-pane tab="附件列表" :key="refKeys[0]" :forceRender="true">
                  <upload
                    :action="url.upload"
                    :download="url.download"
                    @download="handleDownload"
                    @end="handleChange"
                    ref="uploadFile"
                    :fileById="url.fileQuery"
                    buttonType="primary"
                  >
                  </upload>
                </a-tab-pane>
              </a-tabs>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>

    <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
      <a-button @click="submitForm">提 交</a-button>
    </a-col>
  </a-spin>
</template>

<script>
  import { httpAction, getAction, uploadAction, getFileAccessHttpUrl, downloadFile } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'

  export default {
    name: 'HfPmProjectToolRecordsForm',
    components: {},
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false,
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false,
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
      // 树数据
      tree: {
        type: Array,
        default: () => [],
      },
    },
    watch: {
      tree: {
        immediate: true,
        handler(val) {
          this.treeData = val
        },
      },
    },
    data() {
      return {
        form: this.$form.createForm(this),
        model: {},
        uploadAction: '/pm/hfPmProjectTools/uploadFile',
        activeKey: 'busDocument',
        refKeys: ['busDocument'],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {},
        fileId: [],
        headers: {
          authorization: 'authorization-text',
        },
        url: {
          add: '/pm/hfPmProjectRegimeRecords/addRegimeRecord',
          edit: '/pm/hfPmProjectRegimeRecords/editRegimeRecord',
          queryById: '/pm/hfPmProjectRegimeRecords/doPreview',
          upload: '/jeecg-boot/pm/hfPmProjectRegimeRecords/uploadFile',
          download: '/pm/hfPmProjectRegimeRecords/download',
          fileQuery: '/pm/hfPmProjectRegimeRecords/queryHfPmProjectRegimesByMainId',
        },
        treeData: [],
        replaceFields: {
          children: 'children',
          title: 'shortName',
          value: 'id',
          key: 'id',
        },
        dataSource: [],
        validatorRules: {
          parentId: {
            rules: [{ required: true, message: '请选择父级菜单' }],
          },
          title: {
            rules: [{ required: true, message: '请输入名称' }],
          },
          recordType: {
            rules: [{ required: true, message: '请选择工具类型' }],
          },
          id: {
            rules: [{ required: true, message: '请上传附件' }],
          },
        },
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      },
    },
    created() {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData()
    },
    methods: {
      add() {
        this.form.resetFields()
        this.model = Object.assign({})
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'parentId', 'title', 'recordType', 'remarks'))
        })
      },
      close(){
        this.dataSource=[]
        this.model={}
        this.$nextTick(()=>{
          this.$refs.uploadFile.fileList=[]
          this.$refs.uploadFile.tableData=[]
        })
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'parentId', 'title', 'recordType', 'remarks'))
        })
        this.$refs.uploadFile.getNewFile(record)
      },
      //渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId }
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result)
            }
          })
        }
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'parentId', 'title', 'recordType', 'remarks'))
      },
      //  上传附件
      handleChange(info) {
        let id=[]
        if(info.length>0){
          info.map((item)=>{
            id.push({
              id:item.id
            })
            this.fileId=id
          })
        }else {
          this.fileId=[]
        }
      },
      //  附件下载
      handleDownload(record) {
        let fileName=record.name
        let parameter = {
          id: record.id,
        }
        downloadFile(this.url.download, fileName, parameter)
      },
      submitForm() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          values.hfPmProjectRegimesList = this.fileId
          values.isFolder = '0'
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  this.dataSource = []
                } else {
                  that.$message.warning(res.message)
                  this.dataSource = []
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      },
    },
  }
</script>